package com.fg.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.fg.core.FileWrite;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 王富贵
 * @description: 工具线程上下文承载
 * @createTime: 2024年04月20日 09:41:01
 */
@Getter
@Setter
public class ToolsThreadContext {
    private static final TransmittableThreadLocal<ToolsThreadContext> CONTEXT = TransmittableThreadLocal.withInitial(ToolsThreadContext::new);

    /**
     * 输出的表名
     */
    private String dynamicTableName;

    /**
     * 输出sql文件的路径
     */
    private String outputFilePatch;

    /**
     * 输出sql文件的名称
     */
    private String outputFileName;

    /**
     * 通用承载
     */
    private Map<String, Object> map;

    /**
     * 私有
     **/
    private FileWrite fileWrite;

    /**
     * 获取ThreadLocal
     */
    public static ToolsThreadContext get() {
        return CONTEXT.get();
    }

    /**
     * 释放threadLocal的信息，防止线程污染和内存泄露
     */
    public static void remove() {
        CONTEXT.remove();
    }

    public FileWrite secureGetFileWrite() {
        ToolsThreadContext toolsThreadContext = ToolsThreadContext.get();
        FileWrite fileWrite = toolsThreadContext.getFileWrite();
        if (Objects.isNull(fileWrite)) {
            fileWrite = new FileWrite(toolsThreadContext.getOutputFilePatch(), toolsThreadContext.getOutputFileName());
            toolsThreadContext.setFileWrite(fileWrite);
        }
        return fileWrite;
    }


    public void putMap(String key, Object value) {
        if (Objects.isNull(map)) {
            this.map = new HashMap<>();
        }
        map.put(key, value);
    }

    public Object getMap(String key) {
        if (Objects.isNull(map) || StringUtils.isEmpty(key)) {
            return null;
        }
        return map.get(key);
    }
}
